<?php
    $currentFile = $_SERVER["SCRIPT_NAME"];
    $parts = Explode('/', $currentFile);
    $currentFile = $parts[count($parts) - 1];

if($currentFile == 'list.php')
{
    require_once ('..' . DIRECTORY_SEPARATOR . 'initialize.php');
}

include_once(Utils::getPath(array('repositories', 'userRepository.php')));
include_once(Utils::getPath(array('repositories', 'commentRepository.php')));

$commentRep = new CommentRepository();
$userRep = new UserRepository();

$page = !isset($_GET['page']) ? 0 : ($_GET['page'] == 0 ? 0 : $_GET['page'] - 1);

//if is javascript call id and commenttype by GET
if(!isset($id)){
    if(!isset($_GET['id']) || !intval($_GET['id'])){
        Utils::goToErrorPage(StatusCodes::HTTP_BAD_REQUEST);        
    }
    $id = $_GET['id'];
}
if(!isset($commentType)){
    if(!isset($_GET['commentType']) || !intval($_GET['commentType'])){
        Utils::goToErrorPage(StatusCodes::HTTP_BAD_REQUEST);        
    }
    $commentType = $_GET['commentType'];
}

if ($commentType == 1) {
    $comments = $commentRep->getByIdChallenge($id, 'Date', true, $page, 5);
} else if ($commentType == 2) {
    $comments = $commentRep->getByIdSolution($id, 'Date', true, $page, 5);
}

$count = $commentRep->countLast();
$pageMax = ceil($count / 5);

?>
<h3>Comments</h3>
<?php include(Utils::getPath(array('comment', 'new.php'))); ?>
<?php

if ($comments) {
    ?>
    <table id = "comments">
        <?php
        foreach ($comments as $comment) {
            $idComment = $comment->getId();
            $idAuthor = $comment->getIdAuthor();
            $author = $userRep->getById($idAuthor);
            ?>
            <tr class="comment">
                <td class="comment-content">
                    <div class="comment-info">
                        <img alt="User avatar" class="comment-image" src ="<?php echo $author->getImage(); ?>" />
                        <a href="<?php echo Utils::getUrl("user/profile.php?id=$idAuthor") ?>" ><?php echo $author->getUserName(); ?></a><?php echo '  (' . Utils::ago($comment->getDate()) . ')  '; ?>
                        <?php if ($idAuthor == $_SESSION['authenticatedId']) { ?>
                        <a class="button" href="<?php echo Utils::getUrl("comment/delete.php?id=$idComment") ?>">Delete</a>
                        <?php } ?>	
                    </div>
                    <div class="comment-text">
                        <p><?php echo $comment->getText(); ?></p>
                    </div>
                </td>
            </tr>
            <tr class="spacer"></tr>
        <?php
    }
    ?>
    </table>
        <?php
    } else {
        ?>
    <div>No comments. Post one!</div>
    <?php
}
$typestr = ($commentType == 1)? 'challenge': 'solution';
Utils::pagination($page, $pageMax, Utils::getUrl($typestr.'/view.php'));
?>